<script setup>
import { ref,reactive} from 'vue'
import { useRouter } from 'vue-router';
import { ElMessage  } from 'element-plus'; // 使用 Element Plus 的 message 组件
import { userStore } from '@/store/index.js'

import axios from 'axios'
import {Message} from "@element-plus/icons-vue";

const refRuleForm = ref(null)
const router = useRouter()
const store = userStore();

const ruleForm = reactive({
  username: '',
  password: '',
  checkPass: '',
  phone: '',
  validCode: ''
})
const submitForm = ()=>{
  refRuleForm.value.validate((valid) => {
    if (valid) {
      //将注册信息以post方式提交给服务器
      axios.post('/users/register',ruleForm).then(res => {
        const user = res.data;
        // 提示登录成功
        ElMessage({
          message:`用户注册成功，欢迎您：${user.username}`,
          type:'success'
        });
        //更新用户登录的信息
        store.updateUser(user)
        store.updateLoginStatus(true)
        //本地存储
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem("token", res.headers['authorization']);
        //跳转到首页
        router.push('/');

      }).catch(err => {
        console.error(err);  // 打印详细的错误对象
        ElMessage.error(err.response ? err.response.data : '注册失败');
      });
    } else {
      ElMessage.error(`表单验证错误，提交失败！`);
      return false;
    }
  });
}
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 2, max: 20, message: '密码长度在2到20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]*$/, message: '密码只能包含字母和数字', trigger: 'blur' },
  ],
  checkPass: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== ruleForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' },
  ],
  validCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{4}$/, message: '验证码必须是4位数字', trigger: 'blur' },
  ],
});


const smsDisabled = ref(false);  //发短信按钮是否可用
const smsText = ref('发送短信验证码');
const sendSms = () => {
  //验证手机号是否正确
  refRuleForm.value.validateField('phone', error => {
    //如果没有错误，则验证通过
    if (error) {
      //按钮不可用
      smsDisabled.value = true;
      //发送短信
      axios.get(`/users/sendSms/${ruleForm.phone}`).then(resp => {
        //发送成功
        ElMessage({
          message: resp.data,
          type: 'success'
        });
      }).catch(error => {
        //发送失败
        ElMessage.error(error.response.data);
      }).finally(() => {
        //按钮文字变成倒计时
        let seconds = 15;
        smsText.value = `${seconds}秒后重新发送`;
        let timer = setInterval(() => {
          seconds--;
          if (seconds > 0) {
            smsText.value = `${seconds}秒后重新发送`;
          } else {
            //修改文字
            smsText.value = "发送短信验证码";
            //按钮可用
            smsDisabled.value = false;
            //清除定时器
            clearInterval(timer);
          }
        }, 1000);
      });
    }
  });
}
</script>

<template>
  <div class="login-container">
    <el-card class="register-content">
      <span class="register-title">汽车商城：用户注册</span>
      <!-- :rules="rules" 设定校验规则 -->
      <el-form ref="refRuleForm" :model="ruleForm"
               status-icon size="small" :rules="rules" label-width="100px"
               class="demo-ruleForm">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入用户名" style="width: 250px;"></el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password" placeholder="请输入用户密码" style="width: 250px;"></el-input>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" placeholder="请输入确认密码" style="width: 250px;"></el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input type="mobile" v-model="ruleForm.phone" placeholder="请输入正确的手机号" style="width: 250px;"></el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="validCode" label="验证码">
          <div class="valid-code-container">
            <el-input v-model="ruleForm.validCode" placeholder="请输入验证码" style="width: 140px" minlength="4" maxlength="4"></el-input>
            <el-button type="text" :disabled="smsDisabled" @click="sendSms">
              <el-icon :size="20"><Message /></el-icon>
              {{ smsText }}
            </el-button>
          </div>
        </el-form-item>

        <div class="register-submit">
          <el-button type="success" @click="submitForm('ruleForm')" style="width: 150px;" icon="el-icon-user-solid">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  background-image: linear-gradient(135deg, rgb(68, 68, 235), lightblue);  /* 背景渐变 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.register-content {
  margin: 20px;
  border-radius: 10px;
  padding: 30px;
  width: 480px;
  background-color: white; /* 白色背景突出表单 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影提升立体感 */
}

.register-title {
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;  /* 增加标题底部间距 */
}

.demo-ruleForm .el-form-item {
  margin-bottom: 20px;  /* 调整表单项之间的间距 */
}

.el-form-item .el-input {
  width: 100%;  /* 输入框宽度占满 */
}

.valid-code-container {
  display: flex;
  align-items: center; /* 让输入框和按钮垂直居中 */
  gap: 10px;  /* 设置输入框与按钮之间的间距 */
}

.register-submit {
  text-align: center;
  margin-top: 20px;
}

.el-button {
  width: auto;  /* 按钮宽度自适应 */
  height: 40px;
  font-size: 16px;
}

.el-button[type='success'] {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

.el-button[type='text']:hover {
  color: #409EFF;
}
</style>